<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use \tpfcore\Core;
use think\Validate;
use think\Request;
use think\Db;

class Goods extends ApiBase
{
    public function getGodos($data = [])
    {

        $list = Core::loadModel($this->name)->getList($data);

        return [0, 'success', $list];
    }

    public function detail($data=[]){
    	$result = $this->getGodos(["where"=>["id"=>$data['id'],"is_on_sale"=>1,"status"=>1,"is_delete"=>0],"field"=>"id,goods_name,goods_img,goods_thumb,price,market_price,virtual_sales,sales_sum,content,give_integral,stock"])[2];
    	if(empty($result)){
    		return [40040,"产品不存在或已下架"];
    	}
    	// 查询产品图片
    	$result[0]['photo']=Core::loadModel("GoodsPhoto")->getList(["where"=>["goods_id"=>$data['id']]]);

    	// 查询产品属性
    	$listGoodsAttr = Core::loadModel("GoodsAttr")->getList(["where"=>['goods_id'=>$data['id']]]);
    	if($listGoodsAttr){
    		$goods_attribute=[];
    		foreach ($listGoodsAttr as $key => $value) {
    			$goods_attribute[]=$value['attr_id'];
    		}
    		$goods_attribute = array_unique($goods_attribute);
    		

    		$listGoodsAttribute = Core::loadModel("GoodsAttribute")->getList(['where'=>["id"=>["in",$goods_attribute],"select_type"=>1]]);

    		foreach ($listGoodsAttribute as $key => $value) {
    			$cache=[];
    			foreach ($listGoodsAttr as $k => $v) {
    				if($value['id']==$v['attr_id']){
    					$cache[]=$v;
    				}
    			}
    			$listGoodsAttribute[$key]['attr_list']=$cache;
    		}
    		$result[0]['goods_attr']=$listGoodsAttribute;
    	}

        // 查询商品评论
        $listComment = Core::loadModel("GoodsComment")->getList([
            "field"=>"__GOODS_COMMENT__.*,__USER__.headimg",
            "where"=>["__GOODS_COMMENT__.goods_id"=>$data['id'],"display"=>1,"deleted"=>0],
            "join"=>["join"=>"__USER__","condition"=>"__GOODS_COMMENT__.user_id=__USER__.id","type"=>"left"],
            "limit"=>1,
            "order"=>"add_time desc"
        ]);
        //取商品属性列表
        if($listComment){
            $listOrderGoods = Core::loadAddonModel("OrderGoods","mall","controller")->getList([
                "field"=>"spec_key",
                "where"=>["order_id"=>$listComment[0]['order_id'],"goods_id"=>$listComment[0]['goods_id']],
                "limit"=>1
            ]);
            if($listOrderGoods){
                $spec_key_ids = explode(",", $listOrderGoods[0]['spec_key']);
                $listSpecKey = Core::loadAddonModel("GoodsAttr","mall","controller")->getList([
                    "where"=>["id"=>["in",$spec_key_ids]],
                    "field"=>"attr_value"
                ]);
                $arr=[];
                foreach ($listSpecKey as $key => $value) {
                    $arr[]=$value['attr_value'];
                }
                $listComment[0]['spec_str'] = implode(",", $arr);
            }
        }
        //统计购物车里面的数量
        $userInfo = $this->getBaseUserInfo();
        $cartNumber = Core::loadModel("Cart")->getStatistics(["user_id"=>$userInfo['id']],"sum","number");
        $result[0]['cartNumber']=$cartNumber;

        $result[0]['comment']=$listComment;

        // 商家，目前功能没有，后续完善，默认只有一个商家
        $result[0]['seller']=[
            "id"=>1,
            "name"=>"Tcms官方商城",
            "address"=>"重庆江北",
            "thumb"=>"https://gtms04.alicdn.com/tps/i4/TB1x4ExHVXXXXalXFXXSutbFXXX.jpg"
        ];

    	return [0,"success",$result];
    }

    // 获取商品评论
    public function comment($data=[]){
        $limit = isset($data['limit']) && !empty($data['limit']) ? (int)$data['limit'] : 10;

        // 默认查询数据
        $where=["__GOODS_COMMENT__.goods_id"=>$data['id'],"display"=>1,"deleted"=>0];
        $order="id desc";

        if(!empty($data['filter'])){
            switch ($data['filter']) {
                case 1:
                    $order="add_time desc";
                    break;
                case 2:
                    $where["photos"]=["exp","is not null"];
                    break;
                default:
                    # code...
                    break;
            }
        }

        $result  = Core::loadModel("GoodsComment")->getList([
            "field"=>"__GOODS_COMMENT__.*,__USER__.headimg",
            "where"=>$where,
            "join"=>["join"=>"__USER__","condition"=>"__GOODS_COMMENT__.user_id=__USER__.id","type"=>"left"],
            "paginate"=>["rows"=>$limit],
            "order"=>$order
        ]);

        // 取得商品属性
        foreach ($result as $key => $value) {
            $listOrderGoods = Core::loadAddonModel("OrderGoods","mall","controller")->getList([
                "field"=>"spec_key",
                "where"=>["order_id"=>$value['order_id'],"goods_id"=>$value['goods_id']],
                "limit"=>1
            ]);
            if($listOrderGoods){
                $spec_key_ids = explode(",", $listOrderGoods[0]['spec_key']);

                $listSpecKey = Core::loadAddonModel("GoodsAttr","mall","controller")->getList([
                    "where"=>["id"=>["in",$spec_key_ids]],
                    "field"=>"attr_value"
                ]);
                $arr=[];
                foreach ($listSpecKey as $k => $v) {
                    $arr[]=$v['attr_value'];
                }
                $result[$key]['spec_str'] = implode(",", $arr);
            }
        }
        // 统计带图的评论有多少条
        $count = Core::loadModel("GoodsComment")->getStatistics(["goods_id"=>$data['id'],"display"=>1,"deleted"=>0]);

        return [0,$count,$result];
    }
    public function addComment($data){
        if(empty($data['goods'])){
            return [40046,"非法操作"];
        }
        $userInfo = $this->getBaseUserInfo();
        $goodsCommentModel = Core::loadModel("GoodsComment");
        $orderModel = Core::loadAddonModel("Order","mall","controller");
        try {
            Db::startTrans();
            foreach ($data['goods'] as $key => $value) {
                if($orderModel->getStatistics(['id'=>$value['order_id'],"has_comment"=>1])){
                    continue;
                }
                $value['user_id']=$userInfo['id'];
                $value['username']=$userInfo['nickname'];
                $value['ship_rank']=$data['ship_rank'];
                $value['service_rank']=$data['service_rank'];
                $goodsCommentModel->saveObject($value);
                $orderModel->updateObject(['id'=>$value['order_id']],["has_comment"=>1]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return [400045,$e->getMessage()];
        }
        
        return [0,"success"];
    }
    //添加购物车
    /*
        分两种情况
        1、直接添加
        2、更新数据，判断的依据就是：用户user_id，产品id与产品规格
    */
    public function addCart($data=[]){
        $validate = \think\Loader::validate("Cart");
        $validate_result = $validate->scene('addCart')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError(), []];
        }
        $userInfo = $this->getBaseUserInfo();
        $cartModel = Core::loadModel("Cart");

        // 查询产品相关信息
        $list = self::getList([
            "field"=>"goods_sn,goods_name,goods_thumb,price,market_price,stock",
            "where"=>["id"=>$data['id']]
        ]);

        //判断是否已经存在
        $isInCart = $cartModel->getOneObject(['user_id'=>$userInfo['id'],"goods_id"=>$data['id'],"spec_key"=>$data['spec_key']],"id,number");
        if($isInCart){
            if($isInCart['number']+$data['quantity']>$list[0]['stock']){
                return [400046,"商品库存不足"];
            }
            $result = $cartModel->where(['user_id'=>$userInfo['id'],"goods_id"=>$data['id'],"spec_key"=>$data['spec_key']])->setInc("number",$data['quantity']);
        }else{
            $cartData['user_id']=$userInfo['id'];
            $cartData['session_id']=Request::instance()->header("Auth-Token");
            
            $cartData['goods_id']=$data['id'];
            $cartData['goods_sn']=$list[0]['goods_sn'];
            $cartData['goods_name']=$list[0]['goods_name'];
            $cartData['goods_thumb']=$list[0]['goods_thumb'];
            $cartData['goods_price']=$list[0]['price'];
            $cartData['market_price']=$list[0]['market_price'];
            $cartData['number']=$data['quantity'];
            $cartData['spec_key']=$data['spec_key'];
            $cartData['spec_key_name']=$data['spec_key_name'];
            $cartData['add_time']=time();

            $result = $cartModel->saveObject($cartData);
        }
        if($result){
            return [0,"success"];
        }
        return [400048,"添加购物车失败"];
    }
}